package by.yakusekmaxim.bookgid.dataaccess.impl;
import java.util.List;

import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.hibernate.jpa.criteria.OrderImpl;
import org.springframework.stereotype.Repository;

import by.yakusekmaxim.bookgid.dataaccess.ReviewDao;
import by.yakusekmaxim.bookgid.datamodel.Book;
import by.yakusekmaxim.bookgid.datamodel.Review;
import by.yakusekmaxim.bookgid.datamodel.Review_;
import by.yakusekmaxim.bookgid.datamodel.UserAccount;

@Repository
public class ReviewDaoImpl extends AbstractDaoImpl<Long, Review> implements ReviewDao {

    protected ReviewDaoImpl() {
        super(Review.class);
    }

	@Override
	public List<Review> getAllReview(Book book, boolean ascending) {
		CriteriaBuilder cBuilder = getEm().getCriteriaBuilder();

		CriteriaQuery<Review> criteria = cBuilder.createQuery(Review.class);
		Root<Review> root = criteria.from(Review.class);
		criteria.where(cBuilder.equal(root.get(Review_.book), book));
		criteria.select(root);
		criteria.orderBy(new OrderImpl(root.get(Review_.date), ascending));

		TypedQuery<Review> query = getEm().createQuery(criteria);
		List<Review> results = query.getResultList();
		return results;
	}

	@Override
	public List<Review> getReview(Book book, UserAccount user) {
		CriteriaBuilder cBuilder = getEm().getCriteriaBuilder();

		CriteriaQuery<Review> criteria = cBuilder.createQuery(Review.class);
		Root<Review> root = criteria.from(Review.class);
		criteria.where(cBuilder.equal(root.get(Review_.book), book),
				cBuilder.equal(root.get(Review_.userAccount), user));
		criteria.select(root);

		TypedQuery<Review> query = getEm().createQuery(criteria);
		List<Review> results = query.getResultList();
		return results;
	}
}
